package net.rock.eshop.controller;

import net.rock.eshop.entity.Comment;
import net.rock.eshop.entity.User;
import net.rock.eshop.service.CommentService;
import net.rock.eshop.service.UserService;
import net.rock.eshop.utils.UserIdGetter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

class ShowCommentJson {
    int id;
    String username;
    String content;
    int score;

    public ShowCommentJson(int id, String username, String content, int score) {
        this.id = id;
        this.username = username;
        this.content = content;
        this.score = score;
    }
}

@RestController
@RequestMapping("/api/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserIdGetter userIdGetter;

    @GetMapping("/show")
    public List<ShowCommentJson> show(
        int bookId
    ) {
        List<Comment> comments = commentService.fetchByBookId(bookId);

        return comments.stream().map(comment -> {
            User user = userService.fetchUserById(comment.getUserId());
            return new ShowCommentJson(
                    comment.getId(),
                    user.getUsername(),
                    comment.getContent(),
                    comment.getScore()
            );
        }).collect(Collectors.toList());
    }

    @PostMapping("/add")
    public void add(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody Comment comment
    ) {
        // score 在数据库里面进行了合法性校验
        int userId = userIdGetter.getUserIdBySessionId(sessionId);
        comment.setUserId(userId);
        commentService.add(comment);
    }
}
